不同开发语言渲染效果示例
渲染效果如下(由于页面使用大量的黑色元素,这里代码背景不再使用黑色):
C 语言
#include <stdio.h>
#include <stdlib.h>
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
for (int i = 0; i < numsSize; ++i) {
for (int j = i + 1; j < numsSize; ++j) {
if (nums[i] + nums[j] == target) {
int* result = malloc(2 * sizeof(int));
result[0] = i;
result[1] = j;
*returnSize = 2;
return result;
}
}
}
*returnSize = 0;
return NULL;
}
C++
#include <vector>
#include <unordered_map>
class Solution {
public:
std::vector<int> twoSum(std::vector<int>& nums, int target) {
std::unordered_map<int, int> map;
for (int i = 0; i < nums.size(); ++i) {
auto it = map.find(target - nums[i]);
if (it != map.end()) {
return {it->second, i};
}
map[nums[i]] = i;
}
return {};
}
};
Python
def twoSum(nums, target):
hashmap = {}
for i, num in enumerate(nums):
complement = target - num
if complement in hashmap:
return [hashmap[complement], i]
hashmap[num] = i
return []
Java
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No solution");
}
}
Scala
object Solution {
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
val map = scala.collection.mutable.Map[Int, Int]()
for (i <- nums.indices) {
map.get(target - nums(i)) match {
case Some(index) => return Array(index, i)
case None => map(nums(i)) = i
}
}
Array.empty[Int]
}
}
Go
func twoSum(nums []int, target int) []int {
hashMap := make(map[int]int)
for i, num := range nums {
if j, ok := hashMap[target-num]; ok {
return []int{j, i}
}
hashMap[num] = i
}
return nil
}
JavaScript
var twoSum = function(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
return [];
};